<template>
  <div class="layout">
    <Modal v-model="show_key_enter" fullscreen footer-hide>
      <template #close>
        <Icon type="md-close" style="margin: 20px;" size="24" @click.prevent="goBackToHome"/>
      </template>
      <div style="width: 100%;text-align: center;margin-top: 220px;">
        <Input
            v-model="key"
            prefix="md-key"
            placeholder="请输入密码并点击回车..."
            size="large"
            autofocus
            style="width: 400px"
            @keyup.enter="doGetAuthorization"
        />
      </div>
    </Modal>
  </div>
</template>
<script>
import { getAuthorization } from '../../api/authorize'

export default {
  name: 'DocAccessIndex',
  props: ['document_id', 'id'],
  components: {},
  data() {
    return {
      show_key_enter: true,
      key: ''
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      if (!this.document_id) {
        this.$Message.error({
          content: '文档参数缺失，即将返回首页',
          onClose: () => { this.$router.push({ name: 'Index' }) }
        })
      }
    },
    goBackToHome() {
      this.$router.push({ name: 'Index' })
    },
    doGetAuthorization() {
      if (this.document_id < 1) {
        this.$Message.error('文档参数缺失')
        this.$router.push({ name: 'Index' })
        return
      }

      if (this.key.length < 3) {
        this.$Message.error('请输入密码')
        return
      }
      getAuthorization({ key: this.key, document_id: this.document_id }).then((res) => {
        if (res.code === 0 || res.data === false) {
          this.$Message.error(res.msg)
          return
        }

        localStorage.setItem(`document_key_${this.document_id}`, this.key)
        this.$router.push({ path: `/document/${this.document_id}`, query: { id: this.id } })
      }).catch(() => {
        localStorage.setItem(`document_key_${this.document_id}`, '')
      })
    }
  }
}

</script>
<style scoped>
.layout {
  background: #f5f7f9;
  position: relative;
  overflow: hidden;
  min-height: 80vh;
  margin-top: 100px;
}
</style>
